//
//  DSRegisgerController.m
//  DSJY
//
//  Created by 冯华强 on 16/9/24.
//  Copyright © 2016年 dsjy. All rights reserved.
//  注册

#import "DSRegisgerController.h"
#import "DSLeftViewTextField.h"
#import "MTConst.h"
#import "DSRegisgerViewModel.h"
#import "DSAccount.h"
#import "GlobalHeader.h"
#import "DSAccountViewModel.h"
#import "DSWebViewController.h"
#import "MTNavigationController.h"
#import "UIView+Animation.h"
#import "MBProgressHUD+MJ.h"
#import "UITextField+Extension.h"
#import "NSString+Extension.h"

@interface DSRegisgerController ()
#pragma mark - 拖线属性
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet DSLeftViewTextField *nameTextField;
@property (weak, nonatomic) IBOutlet DSLeftViewTextField *pwdTextField;
@property (weak, nonatomic) IBOutlet DSLeftViewTextField *verifyPwdTextField;
@property (weak, nonatomic) IBOutlet DSLeftViewTextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UIButton *regisgerButton;
@property (weak, nonatomic) IBOutlet UIButton *checkBoxButton;

//登录VM
@property (nonatomic, strong) DSRegisgerViewModel *regisgerVM;

@end

@implementation DSRegisgerController

#pragma mark - 懒加载
- (DSRegisgerViewModel *)regisgerVM
{
    if (_regisgerVM == nil) {
        _regisgerVM = [[DSRegisgerViewModel alloc] init];
    }
    return _regisgerVM;
}

#pragma mark - 系统回调
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //显示backItem
    [self setupnavigationItem];
    //1.绑定
    [self bindViewModel];
    //2.事件处理
    [self bindEvent];
    //3.监听通知
    [self setupNotifications];
}

- (void)dealloc
{
    [MTNotificationCenter removeObserver:self];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - 设置UI
- (void)setupnavigationItem
{
    self.showBackItem = YES;
}

- (void)setupNotifications
{
    //监听通知
    [MTNotificationCenter addObserver:self selector:@selector(checkTextField:) name:UITextFieldTextDidChangeNotification object:self.nameTextField];
    [MTNotificationCenter addObserver:self selector:@selector(checkTextField:) name:UITextFieldTextDidChangeNotification object:self.pwdTextField];
    [MTNotificationCenter addObserver:self selector:@selector(checkTextField:) name:UITextFieldTextDidChangeNotification object:self.verifyPwdTextField];
}

- (void)bindViewModel
{
    //1.给试图模型的帐号和密码绑定信号
    RAC(self.regisgerVM.account, loginid) = _nameTextField.rac_textSignal;
    RAC(self.regisgerVM.account, loginPassword) = _pwdTextField.rac_textSignal;
    RAC(self.regisgerVM.account, verifyPassword) = _verifyPwdTextField.rac_textSignal;
    RAC(self.regisgerVM.account, mobile) = _phoneTextField.rac_textSignal;
    
    //1.处理文本狂业务逻辑
    //设置按钮能否点击
    RAC(_regisgerButton, enabled) = self.regisgerVM.regisgerEndSignal;
}

#pragma mark - 设置事件
- (void)bindEvent
{
    @weakify(self);
    [[_regisgerButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        //发送注册请求
        MTLog(@"注册按钮点击");
        [self.regisgerVM.requestCommand execute:nil];
    }];
    
    //获取发送命令的值
    [self.regisgerVM.regisgerCommand.executionSignals.switchToLatest subscribeNext:^(DSAccount *account) {
        @strongify(self);
        //写入用户信息
        //记录密码
        account.loginPassword = self.regisgerVM.account.loginPassword;
        [DSAccountViewModel sharedAccount].account = account;
        [[DSAccountViewModel sharedAccount] write];
        
        //发送通知
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MTNotificationCenter postNotificationName:DSLoginRegisgerSuccessNote object:nil];
            
            //关闭
            [self dismissViewControllerAnimated:YES completion:nil];
            
            if ([self.delegate respondsToSelector:@selector(regisgerControllerDidSuccess:)]) {
                [self.delegate regisgerControllerDidSuccess:self];
            }
        });
    }];
    
    //键盘显示
    [[[MTNotificationCenter rac_addObserverForName:UIKeyboardWillShowNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification *noti) {
        @strongify(self);
        if (!DSIsLandscape) return ;
        CGFloat top = 135;
        if ([self.nameTextField isEditing]) {
            CGFloat f = [self.contentView convertRect:self.nameTextField.frame toView:self.view].origin.y + top;
            [self.contentView keyboardWillTransform:noti eventViewTop:f isHide:NO];
        }else if([self.pwdTextField isEditing]){
            CGFloat f = [self.contentView convertRect:self.pwdTextField.frame toView:self.view].origin.y + top;
            [self.contentView keyboardWillTransform:noti eventViewTop:f isHide:NO];
        }else if([self.verifyPwdTextField isEditing]){
            CGFloat f = [self.contentView convertRect:self.verifyPwdTextField.frame toView:self.view].origin.y + top;
            [self.contentView keyboardWillTransform:noti eventViewTop:f isHide:NO];
        }else if([self.phoneTextField isEditing]){
            CGFloat f = [self.contentView convertRect:self.phoneTextField.frame toView:self.view].origin.y + top;
            [self.contentView keyboardWillTransform:noti eventViewTop:f isHide:NO];
        }
    }];
    
    //键盘隐藏
    [[[MTNotificationCenter rac_addObserverForName:UIKeyboardWillHideNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification *noti) {
        @strongify(self);
        [self.contentView keyboardWillTransform:noti eventViewTop:0 isHide:YES];
    }];
}

//勾选按钮
- (IBAction)checkboxClick:(UIButton *)sender
{
    sender.selected = !sender.isSelected;
    self.regisgerVM.checkBoxSelected = sender.isSelected;
    DSAccount *account = self.regisgerVM.account;
    NSNumber *enabled = @(account.loginid.length && account.loginPassword.length && account.verifyPassword.length && account.mobile.length && self.regisgerVM.checkBoxSelected);
    self.regisgerButton.enabled = [enabled boolValue];
}

//用户协议
- (IBAction)userAgreementClick:(UIButton *)sender
{
    DSWebViewController *webViewVC = [[DSWebViewController alloc] init];
    MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:webViewVC];
    webViewVC.title = @"大思注册用户协议";
    webViewVC.filePath = @"html/UserAgreement";
    [self presentViewController:navVC animated:YES completion:nil];
}

#pragma mark - 用户名通知
- (void)checkTextField:(NSNotification *)noti
{
    UITextField *textField = noti.object;
    if (self.nameTextField == textField) {
        [self textField:textField maxLength:20 block:^{
            [self doNotWantStringtextField:textField];
        }];
    }else if (self.pwdTextField == textField || self.verifyPwdTextField) {
        [self textField:textField maxLength:20 block:^{
        }];
    }
}

- (void)doNotWantStringtextField:(UITextField *)textField
{
    if (![textField textFieldPosition]) {
        textField.text = [textField.text doNotWantString:@"^[^ ]+$" block:^{
//            [MBProgressHUD showText:@"不能包含空格!"];
        }];
    }
}

- (void)textField:(UITextField *)textField maxLength:(NSInteger)maxLength block:(void (^)())block
{
    [textField textFieldMaxLength:maxLength maxBlock:^{
//        [MBProgressHUD showText:@"字数超过最大限制"];
    } completeBlock:^{
        if (block) {
            block();
        }
    }];
}

@end
